package com.fz.utils;


import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

@SuppressWarnings("unchecked")
public class ThrowableUtil {

    /**
     * @param ex
     * @return String 返回类型
     * @throws IOException
     * @Title: getStackTraceAsString
     * @Description: 获取异常堆栈转换为string
     * @author xcc
     */
    public static String getStackTraceAsString(Exception ex) throws Exception {
        /** StringWriter将包含堆栈信息 */
        StringWriter stringWriter = null;
        PrintWriter printWriter = null;
        StringBuffer error = null;
        try {
            //
            stringWriter = new StringWriter();
            /** 必须将StringWriter封装成PrintWriter对象， 以满足printStackTrace的要求*/
            printWriter = new PrintWriter(stringWriter);
            /** 获取堆栈信息 */
            ex.printStackTrace(printWriter);
            printWriter.flush();
            stringWriter.flush();
            /** 转换成String，并返回该String */
            error = stringWriter.getBuffer();
        } finally {
            if (stringWriter != null) {
                try {
                    stringWriter.close();
                } catch (IOException e1) {
                    throw e1;
                }
            }
            if (printWriter != null) {
                printWriter.close();
            }
        }
        return error.toString();
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public static String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}
